package com.minelx.woods.task.core.sql.appender;

import com.alibaba.fastjson.JSONObject;
import com.minelx.statementsplus.common.Templates;
import com.minelx.woods.task.core.sql.SqlCollections;

import java.util.Map;

import static java.util.stream.Collectors.toMap;

public class ContentWithVariablesAppender implements CollectionAppender {
	private final JSONObject result;

	private final JSONObject variables;

	public ContentWithVariablesAppender(JSONObject result, JSONObject variables) {
		this.result = result;
		this.variables = variables;
	}

	@Override
	public void append(SqlCollections sqlCollections) {
		String content = new Templates(result.getString("content")).render(toStringMap(variables));
		sqlCollections.addSqlContent(content);
	}

	private Map<String, String> toStringMap(JSONObject variables) {
		return variables.entrySet().stream()
				.collect(toMap(Map.Entry::getKey, stringObjectEntry -> stringObjectEntry.getValue().toString()));
	}
}
